<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="my-tool-bar">
                <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" rowSelection="multiple" @grid-ready="gridReady" style="height: calc(100% - 45px)" :defaultColDef="defaultColDef"
                class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
                <paginationCopys :total="total" show-total show-jumper show-page-size :page-size="pagination.pageSize"
            :current="pagination.page" @change="PageSize" @page-size-change="change1" style="justify-content: center" />
        </template>
       

        <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label-col-flex="80px" label="寸数" field="dimensionFigure"
                        :rules="[{ required: true, message: '寸数必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" :loading="loading2" :allowClear="true" @search="handleSearch2"
                            v-model="dataForm.dimensionFigure" :filter-option="false" allow-search @focus="focusSel2">
                            <a-option v-for="item in pageData.nameList2" :value="item['dimensionFigure']">{{
                                item['dimensionFigure']
                            }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="机型" field="machineTypeName"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '机型必填' }]">
                        <a-select popup-container="html"  class="bacClass" :allowClear="true" @search="handleSearch1" :loading="loading1"
                            v-model="dataForm.machineTypeName" :filter-option="false" allow-search @focus="focusSel1">
                            <a-option v-for="item in pageData.nameList1" :value="item['typeName']">{{
                                item['typeName']
                            }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="开始重量" field="startWeight"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '开始重量必填' }]">
                        <a-input-number :min="0" :precision="2" class="input-demo bacClass"
                            v-model="dataForm.startWeight" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="结束重量" field="endWeight" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '结束重量必填' }]">
                        <a-input-number :min="0" :precision="2" class="input-demo bacClass" v-model="dataForm.endWeight" />
                    </a-form-item>
                    <!-- <a-form-item v-if="dataForm.startWeight < 0.01" label-col-flex="80px" label="基础值" field="foundation"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '基础值必填' }]">
                        <a-input-number class="input-demo bacClass" v-model="dataForm.foundation" />
                    </a-form-item> -->
                    <a-form-item label-col-flex="80px" label="单价" field="machineTypePrice"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '单价必填' }]">
                        <a-input-number class="input-demo bacClass" v-model="dataForm.machineTypePrice" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="单位" field="unit" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '单位必填' }]">
                        <a-select popup-container="html"  class="bacClass" :allowClear="true" @search="handleSearch3" v-model="dataForm.unit"
                            :loading="loading3" :filter-option="false" allow-search @focus="focusSel3">
                            <a-option v-for="item in pageData.nameList3" :value="item['detailName']">{{
                                item['detailName']
                            }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="备注">
                        <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                            show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>
  
<script setup lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { AnyARecord } from 'dns'

import { localeText } from '@/api/aggridZw'
interface BrandInfo {
    id: any
    remark: string | undefined
    createName: string | undefined
    createTime: string | undefined
    updateName: string | undefined
    updateTime: string | undefined
    deleteState: any

    endWeight: any
    startWeight: any
    machineTypePrice: any
    unit: any
    dimensionFigure: any
    machineTypeName: any
    // foundation: any
}

const total = ref(10)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
    pagination.page = val
    doRefresh()
}

function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
}
const headerShow = ref<boolean>(true)
//查询方法
function doRefresh() {
    pageData.pageLoading = true
    post({
        url: 'pieceData/inchMachinePrice/getPage',
        data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            // disassemblePrice: pageData.dropDownData
        },
    })
        .then(({ data, code }: any) => {
            if (code === 200) {
                table.handleSuccess(data.data)
                gridOption.value.setRowData(data.data)
                total.value = data.total
            }
        })
        .catch(console.log)
        .finally(() => {
            pageData.pageLoading = false
        })
}

const { selectedRowKeys, onSelectionChange } = useRowSelection()
const pagination = usePagination(doRefresh)
const table = useTable()
const rowKey = useRowKey('id')
const tableColumns = useTableColumn([
    {
        title: '寸数',
        key: 'dimensionFigure',
        dataIndex: 'dimensionFigure',
        width: 150,
        // slotName: 'actions',
    },
    {
        title: '机型',
        key: 'machineTypeName',
        dataIndex: 'machineTypeName',
        width: 150,
    },
    {
        title: '单价',
        key: 'machineTypePrice',
        dataIndex: 'machineTypePrice',
        width: 150,
    },
    {
        title: '开始重量',
        key: 'startWeight',
        dataIndex: 'startWeight',
        width: 150,
    },
    {
        title: '结束重量',
        key: 'endWeight',
        dataIndex: 'endWeight',
        width: 150,
    },
    // {
    //     title: '基础值',
    //     key: 'foundation',
    //     dataIndex: 'foundation',
    //     width: 200,
    // },
    {
        title: '单位',
        key: 'unit',
        dataIndex: 'unit',
        width: 150,
    },
    {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 200,
    },
    {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
    },
    {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
    },
    {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
    },
    {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
    },
    {
        title: '操作',
        key: 'id',
        slotName: 'act',
        width: 150,
        fixed: 'right',
    },
])
let tc: any[] = tableColumns.map((o) => {
    let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
    }
    if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80

        obj['cellRenderer'] = {
            // template: `<a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag>`,
            template: `<el-button style="color:#165dff;"  v-if="isEdit" type="info" link @click="a">修改</el-button>`,
            setup(props: any) {
                const a = () => {
                    editHandler(props.params.data)
                }
                let isEdit = permissionStore.hasPermisson('csdj.xg')
                return {
                    a,
                    isEdit,
                }
            },
        }
    }
    if (o.slotName === 'actions') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['cellRenderer'] = {
            template: `<a-space>
            <a-tag class="tagCss" style="color:#165dff !important" v-if="a.openNot ==0" >否</a-tag>
            <a-tag v-if="a.openNot ==1" class="tagCss" style="color:#909399 !important">是</a-tag>
           </a-space>`,
            setup(props: any) {
                return {
                    a: props.params.data,
                }
            },
        }
    }

    return obj
})

let a = [
    {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
    },
]
tc = a.concat(tc)

const pageData = reactive<{
    showAdd: boolean
    sideTitle: string
    dropDownData: any
    nameList1: []
    nameList2: []
    nameList3: []
    pageLoading: boolean
    typeList: []
    rHeight: any
    btnList: any[]
    isEdit: boolean
}>({
    nameList1: [],
    nameList2: [],
    nameList3: [],
    showAdd: false,
    sideTitle: '新增值机绩效计产方案',
    dropDownData: '',
    pageLoading: false,
    typeList: [],
    rHeight: 0,
    btnList: [],
    isEdit: false,
})


onMounted(() => {
    // 切换tap到本页面执行的方法
    emitter.on('FabricPrice2', () => {
        doRefresh()
    })
})

let cxbl = {}
//查询
const selectHandler = () => {
    pagination.page = 1
    cxbl = pageData.dropDownData
    doRefresh()
}
const queryData = reactive({
    disassemblePrice: '',
})
const addHandler = () => {
    for (var key in dataForm) {
        if (key === 'id') {
            dataForm[key] = null
        } else {
            dataForm[key] = ''
        }
    }
    pageData.showAdd = true
    pageData.sideTitle = '新增值机绩效计产方案'
}
const dataForm = reactive<BrandInfo>({
    id: null,
    remark: '',
    createName: '',
    createTime: '',
    updateName: '',
    updateTime: '',
    deleteState: 0,

    dimensionFigure: '',
    machineTypePrice: null,
    machineTypeName: null,
    unit: '',
    startWeight: null,
    endWeight: null,
    // foundation: null,
})

// 表格准备事件
const gridOption = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
}

const formRef = ref<FormInstance>()
const sideOk = () => {
    formRef.value?.validate().then((err) => {
        if (!err) {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    pageData.pageLoading = true
                    if (pageData.sideTitle === '新增值机绩效计产方案') {
                        post({
                            url: 'pieceData/inchMachinePrice/insert',
                            data: [dataForm],
                        })
                            .then((res: any) => {
                                if (res.code === 200) {
                                    formRef.value?.resetFields()
                                    pageData.showAdd = false
                                    Message.success({
                                        content: '新增成功',
                                        duration: 5000,
                                    })
                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000,
                                    })
                                }
                                doRefresh()
                            })
                            .finally(() => {
                                doRefresh()
                                pageData.pageLoading = false
                            })
                    } else {
                        post({
                            url: 'pieceData/inchMachinePrice/update',
                            data: [dataForm],
                        })
                            .then((res: any) => {
                                if (res.code === 200) {
                                    formRef.value?.resetFields()
                                    pageData.showAdd = false
                                    Message.success({
                                        content: '修改成功',
                                        duration: 5000,
                                    })
                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000,
                                    })
                                }
                                //doRefresh();
                            })
                            .finally(() => {
                                doRefresh()
                                pageData.pageLoading = false
                            })
                    }
                }
            })
        }
    })
}
const deleteHandler = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
    }
    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
            pageData.pageLoading = true
            post({
                url: 'pieceData/inchMachinePrice/delete',
                data: gridOption.value.getSelectedRows().map((o: any) => {
                    return o.id
                }),
            })
                .then(({ code, data }: any) => {
                    if (code === 200) {
                        Message.success({
                            content: '删除成功',
                            duration: 5000,
                        })
                        pagination.page = 1
                        doRefresh()
                    } else {
                        Message.error({
                            content: '删除失败',
                            duration: 5000,
                        })
                    }
                })
                .finally(() => {
                    pageData.pageLoading = false
                })
        },
    })
}
const editHandler = (record: BrandInfo) => {
    //循环对象 赋值
    for (let key in record) {
        dataForm[key] = record[key]
    }
    dataForm.startWeight = Number(record.startWeight)
    dataForm.endWeight = Number(record.endWeight)
    dataForm.machineTypePrice = Number(record.machineTypePrice)
    // dataForm.foundation = Number(record.foundation)
    pageData.sideTitle = '修改值机绩效计产方案'
    pageData.showAdd = true
}
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
    return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
    })
}
//input离开焦点 将小写转大写
const inputBlur = () => {
    dataForm.unit = dataForm.unit.toUpperCase()
}

const handleChange = (_data: any) => {
    table.handleSuccess(_data)
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    // flex: 1
}
const localeText1: any = ref(localeText)
//  :items="['查询', '新增', '删除']"
//设置权限
const permissionStore = usePermission()
if (permissionStore.hasPermisson('csdj.cx')) {
    pageData.btnList.push('查询')
}
if (permissionStore.hasPermisson('csdj.xz')) {
    pageData.btnList.push('新增')
}
if (permissionStore.hasPermisson('csdj.sc')) {
    pageData.btnList.push('删除')
}

const focusSel1 = () => {
    selCxAll1({ typeName: '' })
}
const options1 = ref<any>(pageData.nameList1)
const loading1 = ref(false)
const handleSearch1 = (value: any) => {
    if (value) {
        const ob = { typeName: value }
        loading1.value = true
        selCxAll1(ob)
        options1.value = pageData.nameList1
        loading1.value = false
    } else {
        options1.value = []
    }
}
function selCxAll1(val: any) {
    post({
        url: 'planSingle/machineType/getFieldValue',
        data: val,
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.nameList1 = data
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}

const focusSel2 = () => {
    selCxAll2({ dimensionFigure: '' })
}
const options2 = ref<any>(pageData.nameList2)
const loading2 = ref(false)
const handleSearch2 = (value: any) => {
    if (value) {
        const ob = { dimensionFigure: value }
        loading2.value = true
        selCxAll2(ob)
        options2.value = pageData.nameList2
        loading2.value = false
    } else {
        options2.value = []
    }
}
function selCxAll2(val: any) {
    post({
        url: 'product/pdGreyInformation/getFieldValue2',
        data: val,
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.nameList2 = data
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}

const focusSel3 = () => {
    selCxAll3({ codeType: '' })
}
const options3 = ref<any>(pageData.nameList3)
const loading3 = ref(false)
const handleSearch3 = (value: any) => {
    if (value) {
        const ob = { codeType: value }
        loading3.value = true
        selCxAll3(ob)
        options3.value = pageData.nameList3
        loading3.value = false
    } else {
        options3.value = []
    }
}
function selCxAll3(val: any) {
    post({
        url: 'dict/dictTypeDetail/getList',
        data: { codeType: 17 }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.nameList3 = data
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}
</script>
<script lang="ts">
export default {
    name: "FabricPrice2",
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>